//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package sw_store_api_serv

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/sw_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/sw_store_api"
)

type SwStoreApiImpl struct {
	sw_store_api.UnimplementedSwStoreApiServer
}

func (apiImpl *SwStoreApiImpl) ListCate(ctx context.Context, req *sw_store_api.ListCateRequest) (*sw_store_api.ListCateResponse, error) {
	cateItemList, err := sw_dao.CateDao.List(ctx)
	if err != nil {
		return nil, err
	}
	cateList := []*sw_store_api.SoftWareCateInfo{}
	for _, cateItem := range cateItemList {
		cateList = append(cateList, cateItem.ToSoftWareCateInfo())
	}
	return &sw_store_api.ListCateResponse{
		Code:     sw_store_api.ListCateResponse_CODE_OK,
		CateList: cateList,
	}, nil
}

func (apiImpl *SwStoreApiImpl) ListSoftWare(ctx context.Context, req *sw_store_api.ListSoftWareRequest) (*sw_store_api.ListSoftWareResponse, error) {
	cateItemList, err := sw_dao.CateDao.List(ctx)
	if err != nil {
		return nil, err
	}
	cateNameMap := map[string]string{}
	for _, cateItem := range cateItemList {
		cateNameMap[cateItem.CateId] = cateItem.CateName
	}

	count, err := sw_dao.SoftwareDao.Count(ctx, req.ListParam)
	if err != nil {
		return nil, err
	}
	softwareItemList, err := sw_dao.SoftwareDao.List(ctx, req.ListParam, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}

	softwareList := []*sw_store_api.SoftWareInfo{}
	for _, softwareItem := range softwareItemList {
		software := softwareItem.ToSoftWareInfo()
		software.CateName = cateNameMap[softwareItem.CateId]
		softwareList = append(softwareList, software)
	}

	return &sw_store_api.ListSoftWareResponse{
		Code:         sw_store_api.ListSoftWareResponse_CODE_OK,
		TotalCount:   count,
		SoftWareList: softwareList,
	}, nil
}

func (apiImpl *SwStoreApiImpl) GetSoftWare(ctx context.Context, req *sw_store_api.GetSoftWareRequest) (*sw_store_api.GetSoftWareResponse, error) {
	emptySoftware := &sw_store_api.SoftWareInfo{
		OsList: []sw_store_api.OS_TYPE{},
	}

	softwareItem, err := sw_dao.SoftwareDao.Get(ctx, req.SwId)
	if err != nil {
		return &sw_store_api.GetSoftWareResponse{
			Code:     sw_store_api.GetSoftWareResponse_CODE_NO_SOFT_WARE,
			ErrMsg:   "软件不存在",
			SoftWare: emptySoftware,
		}, nil
	}

	cateItem, err := sw_dao.CateDao.Get(ctx, softwareItem.CateId)
	if err != nil {
		return nil, err
	}
	software := softwareItem.ToSoftWareInfo()
	software.CateName = cateItem.CateName

	return &sw_store_api.GetSoftWareResponse{
		Code:     sw_store_api.GetSoftWareResponse_CODE_OK,
		SoftWare: software,
	}, nil
}
